package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/orm"
	"errors"
)

var Area = new(areaService)

type areaService struct{}

func (s *areaService) List(req *model.ReqArea) (*[]model.ResponseArea, error) {
	// 分页
	list := make([]tables.Area, 0)
	query := orm.Db.Asc("id")
	level := 1
	pid := 0
	if req.Province != 0 {
		pid = req.Province
		level = 2
	}
	if req.City != 0 {
		pid = req.City
		level = 3
	}
	query.Where("pid = ?", pid)
	query.Where("level = ?", level)
	err := query.Find(&list)
	//判断子账户
	if err != nil {
		return nil, err
	}
	var m []model.ResponseArea
	for _, item := range list {
		m = append(m, model.ResponseArea{
			Value: item.Id,
			Name:  item.Name,
		})
	}
	return &m, nil
}
func (s *areaService) InfoById(id int, field string) (*tables.Area, error) {
	user := new(tables.Area)
	has, err := orm.Db.ID(id).Cols(field).Get(user)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("地址信息不存在")
	}
	return user, nil
}
func (s *areaService) InfoByAreaId(name string, pid int, field string) (*tables.Area, error) {
	user := new(tables.Area)
	has, err := orm.Db.Where("name = ? and pid = ?", name, pid).Cols(field).Get(user)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("地址信息不存在")
	}
	return user, nil
}
